package cz.cvut.fel.gfupan.gui.action;

import cz.cvut.fel.gfupan.gui.component.AutoCompleteBox;
import cz.cvut.fel.gfupan.gui.Window;
import cz.cvut.fel.gfupan.gui.util.AutoCompleteItem;
import cz.cvut.fel.gfupan.gui.util.AutoCompleteList;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;

public class AutoCompleteKeyListener extends KeyAdapter {

    private AutoCompleteBox combo;
    private Window window;

    public AutoCompleteKeyListener(Window window, AutoCompleteBox root) {
        this.combo = root;
        this.window = window;
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_F1 || code == KeyEvent.VK_F2 || code == KeyEvent.VK_F3 || code == KeyEvent.VK_F4 || code == KeyEvent.VK_F5
                || code == KeyEvent.VK_F6 || code == KeyEvent.VK_F7) {
            return;
        }
        String a = combo.getEditor().getItem().toString();

        if (code == KeyEvent.VK_ENTER) {
            AutoCompleteItem result = AutoCompleteList.find(new AutoCompleteItem(a), combo.items());
            if (result != null) {
                window.showElementByMeasureAndId(result.measure, result.tab, result.id);
            }
        }

        if (code != KeyEvent.VK_UP && code != KeyEvent.VK_DOWN && code != KeyEvent.VK_ENTER) {
            combo.removeAllItems();
            boolean showPopup = false;

            for (AutoCompleteItem v : combo.items()) {
                if (v.name.startsWith(a)) {
                    combo.addItem(v.toString());
                    showPopup = true;
                }
            }

            combo.getEditor().setItem(a);
            JTextField textField = (JTextField) e.getSource();
            textField.setCaretPosition(textField.getDocument().getLength());
            combo.hidePopup();

            if (showPopup) {
                combo.showPopup();
            }
        }
    }
}
